<template>
  <div class="prompt-display">
    <div class="header">
      <div class="header-content">
        <button class="back-button" @click="goToChat">
          <span class="back-icon">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
          </span>
          <span class="back-text">继续对话</span>
        </button>
        <div class="title-section">
          <h2>Prompt 配置</h2>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="error" class="error-state">
      <i class="error-icon">⚠️</i>
      <span>{{ error }}</span>
    </div>
    
    <div v-else class="prompts-container">
      <ul v-if="prompts && prompts.length" class="prompt-list">
        <li v-for="(prompt, index) in prompts" 
            :key="index" 
            class="prompt-item"
            :class="{ 'editing': editingIndex === index }">
          <div class="prompt-header">
            <h3>{{ prompt.name }}</h3>
          </div>
          <div class="prompt-content">
            <pre v-if="editingIndex !== index" 
                 @dblclick="startEdit(index)" 
                 :title="'双击编辑'"
                 class="prompt-text">{{ prompt.prompt }}</pre>
            <div v-else class="edit-area">
              <div class="edit-header">
                <span class="edit-title">正在编辑</span>
                <div class="edit-actions">
                  <button class="edit-btn save-btn" @click="saveEdit(prompt.name)">
                    <span class="btn-icon">✓</span>
                    保存
                  </button>
                  <button class="edit-btn cancel-btn" @click="cancelEdit">
                    <span class="btn-icon">✕</span>
                    取消
                  </button>
                </div>
              </div>
              <textarea 
                v-model="editingContent"
                @keydown.esc="cancelEdit"
                :ref="el => { if (el) editTextarea = el }"
                class="edit-textarea"
                autofocus
              ></textarea>
              <div class="edit-footer">
                <div class="edit-tips">
                  <span class="tip-item">
                    <span class="tip-icon">⌘</span>
                    <span>ESC 取消</span>
                  </span>
                  <span class="tip-item">
                    <span class="tip-icon">⌘</span>
                    <span>Enter 换行</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <div v-else class="empty-state">暂无 Prompt 配置</div>
    </div>
  </div>
</template>

<style scoped>
.prompt-display {
  max-width: 1200px;
  min-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f2f5;
}

.header-left {
  margin-right: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e3f2fd;
}

.back-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #ffffff;
  color: #1976d2;
  border: 1px solid #e3f2fd;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(25, 118, 210, 0.05);
  height: 36px;
}

.back-button:hover {
  background-color: #1976d2;
  color: #ffffff;
  border-color: #1976d2;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(25, 118, 210, 0.15);
}

.back-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(25, 118, 210, 0.1);
}

.back-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  transition: transform 0.2s ease;
}

.back-button:hover .back-icon {
  transform: translateX(-2px);
}

.back-text {
  font-weight: 500;
  letter-spacing: 0.3px;
}

.header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.prompts-container {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.prompt-list {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.prompt-item {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 20px;
  transition: all 0.3s ease;
}

.prompt-item:hover {
  border-color: #90caf9;
  box-shadow: 0 2px 12px rgba(25, 118, 210, 0.1);
}

.prompt-item.editing {
  border-color: #1976d2;
  background: #fff;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.prompt-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.prompt-header h3 {
  margin: 0;
  color: #1976d2;
  font-size: 18px;
  font-weight: 500;
}

.prompt-content {
  position: relative;
}

.prompt-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
  line-height: 1.6;
  color: #2c3e50;
  cursor: pointer;
  padding: 12px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.prompt-text:hover {
  background-color: #e3f2fd;
}

.edit-area {
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin: 8px 0;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.edit-title {
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.edit-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.save-btn {
  background-color: #1976d2;
  color: white;
}

.save-btn:hover {
  background-color: #1565c0;
}

.cancel-btn {
  background-color: #f1f5f9;
  color: #64748b;
  border-color: #e2e8f0;
}

.cancel-btn:hover {
  background-color: #e2e8f0;
  color: #475569;
}

.btn-icon {
  font-size: 14px;
  line-height: 1;
}

.edit-textarea {
  width: 100%;
  min-height: 150px;
  padding: 16px;
  border: none;
  background: #ffffff;
  color: #1e293b;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
  box-sizing: border-box;
}

.edit-textarea:focus {
  outline: none;
}

.edit-footer {
  padding: 8px 16px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.edit-tips {
  display: flex;
  gap: 16px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #64748b;
}

.tip-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background: #e2e8f0;
  border-radius: 3px;
  font-size: 10px;
  font-weight: 500;
}

/* 动画效果 */
.edit-area {
  animation: slideIn 0.2s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.loading-state, .error-state, .empty-state {
  padding: 40px;
  text-align: center;
  color: #666;
  background: #f8fafc;
  border-radius: 8px;
  margin: 20px 0;
}

.loading-spinner {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid #e3f2fd;
  border-radius: 50%;
  border-top-color: #1976d2;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

.error-icon {
  margin-right: 8px;
  font-size: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .prompt-display {
    padding: 15px;
  }
  
  .prompt-item {
    padding: 15px;
  }
  
  .header h2 {
    font-size: 20px;
  }
}

.title-section {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.title-section h2 {
  margin: 0;
  color: #1976d2;
  font-size: 22px;
  font-weight: 600;
  letter-spacing: -0.5px;
}

.header-desc {
  color: #64748b;
  font-size: 14px;
  font-weight: 400;
}
</style>

<script>
import { API_BASE_URL } from '../config'
import { useRouter } from 'vue-router'

export default {
  name: 'PromptDisplay',
  data() {
    return {
      prompts: null,
      loading: true,
      error: null,
      editingIndex: -1,
      editingContent: '',
      baseUrl: API_BASE_URL,
      retryCount: 3,
      editTextarea: null
    }
  },
  async created() {
    await this.fetchPrompts()
  },
  setup() {
    const router = useRouter()
    return {
      goToChat() {
        router.push('/')  // 导航到主页（聊天界面）
      }
    }
  },
  methods: {
    async fetchPrompts(retries = this.retryCount) {
      try {
        console.log('正在获取 Prompts...')
        console.log('请求URL:', `${this.baseUrl}/api/prompts`)
        
        const response = await fetch(`${this.baseUrl}/api/prompts`, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        })
        
        console.log('响应状态:', response.status)
        
        if (!response.ok) {
          const errorText = await response.text()
          console.error('错误响应内容:', errorText)
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        console.log('获取到的原始数据:', data)
        
        if (!data || !data.prompts) {
          console.error('数据格式不正确 - 缺少 prompts 字段:', data)
          throw new Error('数据格式不正确')
        }
        
        this.prompts = data.prompts
        console.log('处理后的 prompts:', this.prompts)
        
      } catch (error) {
        console.error('获取 Prompts 失败:', error)
        console.error('错误堆栈:', error.stack)
        
        if (retries > 0) {
          console.log(`还剩 ${retries} 次重试机会`)
          await new Promise(resolve => setTimeout(resolve, 1000))
          return this.fetchPrompts(retries - 1)
        }
        this.error = `加载 Prompts 失败: ${error.message}`
      } finally {
        this.loading = false
      }
    },

    startEdit(index) {
      this.editingIndex = index
      this.editingContent = this.prompts[index].prompt || ''
      this.$nextTick(() => {
        if (this.editTextarea) {
          this.editTextarea.focus()
        }
      })
    },

    cancelEdit() {
      this.editingIndex = -1
      this.editingContent = ''
    },

    async saveEdit(promptName) {
      try {
        const response = await fetch(`${this.baseUrl}/api/prompts`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: promptName,
            new_prompt: this.editingContent
          })
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.success) {
          const promptIndex = this.prompts.findIndex(p => p.name === promptName)
          if (promptIndex !== -1) {
            this.prompts[promptIndex].prompt = this.editingContent
          }
          this.editingIndex = -1
          this.editingContent = ''
        } else {
          alert(result.message || '更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        alert(`更新失败: ${error.message}`)
      }
    }
  },
  emits: ['back']
}
</script> 